package com.myproject.myblogserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

import com.myproject.myblogserver.contant.CommonConstants;
import com.myproject.myblogserver.entity.Blog;
import com.myproject.myblogserver.entity.FavoriteFolder;
import com.myproject.myblogserver.entity.FolderBlog;
import com.myproject.myblogserver.service.IBlogService;
import com.myproject.myblogserver.service.IFavoriteFolderService;
import com.myproject.myblogserver.service.IFolderBlogService;
import com.myproject.myblogserver.utils.JwtUtil;

/**
 * <p>
 * 收藏夹-博客关联表 前端控制器
 * </p>
 *
 * @author jiangweike
 * @since 2025-02-16
 */
@Controller
@RequestMapping("/folderBlog")
public class FolderBlogController {

    @Autowired
    private IFolderBlogService folderBlogService;

    @Autowired
    private IFavoriteFolderService favoriteFolderService;

    @Autowired
    private IBlogService blogService;

    /**
     * 添加博客到收藏夹
     */
    @PostMapping("/add/{folderId}/{blogId}")
    public ResponseEntity<?> addBlogToFolder(
            @PathVariable Long folderId,
            @PathVariable Long blogId,
            @RequestHeader("Authorization") String authHeader) {
        try {
            var userId = JwtUtil.extractUserIdFromAuthHeader(authHeader);

            // 验证收藏夹是否存在且属于当前用户
            var folder = favoriteFolderService.lambdaQuery()
                    .eq(FavoriteFolder::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(FavoriteFolder::getId, folderId)
                    .eq(FavoriteFolder::getUserId, userId)
                    .one();

            if (folder == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("收藏夹不存在或无权限操作！");
            }

            // 验证博客是否存在
            var blog = blogService.lambdaQuery()
                    .eq(Blog::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(Blog::getId, blogId)
                    .one();

            if (blog == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("博客不存在！");
            }

            // 检查是否已经收藏过
            var existingRecord = folderBlogService.lambdaQuery()
                    .eq(FolderBlog::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(FolderBlog::getFolderId, folderId)
                    .eq(FolderBlog::getBlogId, blogId)
                    .one();

            if (existingRecord != null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("该博客已在收藏夹中！");
            }

            // 创建新的收藏记录
            var folderBlog = new FolderBlog();
            folderBlog.setFolderId(folderId);
            folderBlog.setBlogId(blogId);
            folderBlogService.save(folderBlog);

            return ResponseEntity.ok("添加博客到收藏夹成功！");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("添加博客到收藏夹失败！");
        }
    }

    /**
     * 从收藏夹删除博客
     */
    @PostMapping("/remove/{folderId}/{blogId}")
    public ResponseEntity<?> removeBlogFromFolder(
            @PathVariable Long folderId,
            @PathVariable Long blogId,
            @RequestHeader("Authorization") String authHeader) {
        try {
            var userId = JwtUtil.extractUserIdFromAuthHeader(authHeader);

            // 验证收藏夹是否属于当前用户
            var folder = favoriteFolderService.lambdaQuery()
                    .eq(FavoriteFolder::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(FavoriteFolder::getId, folderId)
                    .eq(FavoriteFolder::getUserId, userId)
                    .one();

            if (folder == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("收藏夹不存在或无权限操作！");
            }

            // 查找收藏记录
            var folderBlog = folderBlogService.lambdaQuery()
                    .eq(FolderBlog::getIsDeleted, CommonConstants.DELETED_STATUS_NO)
                    .eq(FolderBlog::getFolderId, folderId)
                    .eq(FolderBlog::getBlogId, blogId)
                    .one();

            if (folderBlog == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("未找到收藏记录！");
            }

            // 软删除收藏记录
            folderBlogService.lambdaUpdate()
                    .set(FolderBlog::getIsDeleted, CommonConstants.DELETED_STATUS_YES)
                    .eq(FolderBlog::getId, folderBlog.getId())
                    .update();

            return ResponseEntity.ok("从收藏夹删除博客成功！");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("从收藏夹删除博客失败！");
        }
    }
}
